document.write("<script language=javascript src='./js/api.js'></script>");
document.write("<script language=javascript src='./json/range.js'></script>");
document.write("<script language=javascript src='./json/HDZBNew.js'></script>");
var coorNum = 0
var constructionList = [] // 总工地列表
var activitiesList = []  //活动数量
// var x = 3366;
// var y = 1547;
// var zoom = 12;
// var tilesUrlsErrorCount = 0; //记录图斑地址错误次数
// var tilesUrlsStatus = true; 
var mapTypeJson = {
  enableMapClick: false,
  // mapType: BMAP_HYBRID_MAP,
  minZoom: 11,
  maxZoom: 18,
};
var map = new BMap.Map("mappart", mapTypeJson)//设置最大和最小缩放级别);
map.centerAndZoom(new BMap.Point(116.228893, 40.02077), 12);//初始化显示级别和位置
map.enableScrollWheelZoom();//开启滚动缩放地图
// 获取北京市一张图
function getBJPicture(){
  var imagesTileLayer = new BMap.TileLayer({
    zIndex: 1,
  });
  imagesTileLayer.getTilesUrl = function (tileCoord, zoom) {
    var x = tileCoord.x;
    var y = tileCoord.y;
    var url = 'http://11.16.125.18:8081/tiles/' + zoom + '/' + x + '/' + y + '.jpg';
    return url;
  }
  map.addTileLayer(imagesTileLayer);
}


// 获取海淀一张图
function getHDPicture (years){
  var years_url=  getPreMonth(years)
  
  var tileLayer = new BMap.TileLayer({
    zIndex: 2,
  });
  tileLayer.getTilesUrl = function (tileCoord, zoom) {
    var x = tileCoord.x;
    var y = tileCoord.y;
    var url = 'http://11.16.127.137:8082/haidian_' + years_url +
      '/token833769810323949CFCB9C89C7B6733D1/wmts/haidian_' + years_url +
      '/webmercator/WTMS/haidian_' + years_url + '/webmercator/' + zoom + '/' + x + '/' + y + '.png';
    if (!validateImage(url)){
      years_url = getPreMonth(years_url)
    }
    return url;
  }
  map.addTileLayer(tileLayer);
}

//绘制海淀区区域
function drawHaiDian(){
  let PathrangeMap = pointArray
  var xcq = new BMap.Polygon(PathrangeMap, {
      strokeWeight: 2,
      strokeColor: "#41b0fd",
      strokeStyle: "solid",
      fillOpacity: 0.2,
      fillColor: "#0053A9"
    }); //建立多边形覆盖物
    map.addOverlay(xcq);
    xcq.disableMassClear();
}
// 绘制北京区域
function drawBeiJing () {
  let PathrangeMap = beijingMap
  var xcq = new BMap.Polygon(PathrangeMap, {
    strokeWeight: 2,
    strokeColor: "#009fff",
    strokeStyle: "solid",
    fillOpacity: 0.2,
    fillColor: "#003bd0"
  }); //建立多边形覆盖物
  map.addOverlay(xcq);
  xcq.disableMassClear();
}

// 绘制城镇的区域线
function getDrawTown (coordinates) {
  var path = []
  coordinates.forEach(item => {
    path = [...path, ...[new BMap.Point(item.lng, item.lat)]]
  })
  var polygon = new BMap.Polygon(path, { strokeColor: "#2292FF", strokeWeight: 1, strokeStyle: "dashed", strokeOpacity: 0, fillOpacity: 0.1, fillColor: '#0f0f0f' });
  map.addOverlay(polygon);
  polygon.disableMassClear();
}
// 引入街道经纬度
function getonload () {
  districtAreaData.forEach(item=>{
    getDrawLabel(item.center_point.lng, item.center_point.lat, item.name)
    getDrawTown(item.points)
  })
}
// function get
// 给街道添加label
function getDrawLabel (lng, lat, content){
  var point = new BMap.Point(lng, lat);
  var label = new BMap.Label(content, {
    position: point,
    offset: new BMap.Size(10, 20)
  })
  map.addOverlay(label);  
  label.setStyle({
    color: '#D4F0FF',
    fontSize: '14px',
    border: '0px solid #1E90FF',
    backgroundColor:'rgba(255,255,0,0)',
    width:'80px',
    fontWeight:'bold',
    fontFamily:'Microsoft YaHei'
  })
  label.disableMassClear();
}
// 获取左侧总数量
function getTotalQuantity (month, state,type){
  let param = {
    month:month,
    state: state,
    type: type
  }
  indexAjax('GET', api.queryAllCount, param, function (res){
    $("#totalNum").text(res.allCount)
    $("#warnNum").text(res.warningCount)
    $("#monitorNum").text(res.monitorCount)
    $("#LockNum").text(res.lockCount)

  })
}

// 绘制不同类型的工地区域图
// 中心点  周边坐标 
// 颜色值 {}
function getConstruction (type, coordinates) {
  var typeObj = {
    '1': '#D73300',
    '2': '#00DC81',
    '3': '#D98900',
    '4': '#FFF442',
    '5': 'red',
    '6': 'green'
  }
  var path = []
  coordinates[0].forEach(item => {
    path = [...path, ...[new BMap.Point(item[0], item[1])]]
  })
  var polygon = new BMap.Polygon(path, { strokeColor: typeObj[type], strokeWeight: 5, strokeOpacity: 0.5, fillOpacity: 0.1, fillColor:'#ffffff' });
  let urlNu = `devid=${coordinates[1].id}&point=${coordinates[1].lat},${coordinates[1].lon}`
  polygon.customData = {
    _url: urlNu
  }
  map.addOverlay(polygon);
  polygon.addEventListener("click", attribute);
}
// 地图点击事件
map.addEventListener('click', function (e) {


});
// 获取全部工地的坐标 描边 type 查询的类型  date 日期 Clitype 是否描边
function getAllSiteMap (type, date, Clitype){
  let times = getFLDay(date.substr(0, 4), date.substr(5, 2))
  let param = {
    state: type,
    beginTime: times[0],
    endTime: times[1]
  }
  indexAjax('GET', api.findAllTwo, param, function (res) {
    // $("#totalNum").text(`${res.list[0].total}`)
    if (Clitype) {
      map.clearOverlays();
      res.list[0].allLocation.forEach(item => {
        let coordinatesObj = JSON.parse(item.FANGWU)
        getConstruction(item.TYPE, [coordinatesObj.coordinates[0], { id: item.BUILDINGSITENUM, lat: item.CENTRALLAT, lon: item.CENTRALLON }])
      })
    }
  })
}
// 获取左侧 全部工地的list  是否追加
function getAllMapList (type, date){
  let times = getFLDay(date.substr(0, 4), date.substr(5, 2))
  let param = {
    state: type,
    beginTime: times[0],
    endTime: times[1]
  }
  var typeNames = {
    '1': '在建工地 ',
    '2': '市政',
    '3': '装修',
    '5': '拆迁工地'
  }
  indexAjax('GET', api.findStreetInfo, param, function (res) {
    var streetInfo = res.list[0]
    var listAll = res.list[0].listAll
    var totalHtml = `<div class="box-nr-tit">
          <img src="images/dingwei.png" />
          全区情况
        </div>
        <div class="box-nr-xx" id="totalXX">
          <ul class="box-nr-table box-nr-table-header">
            <li>工程状态</li>
            <li>总面积(㎡)</li>
            <li>总数量</li>
          </ul>
        </div>`
    listAll.forEach(item => {
      totalHtml = `${ totalHtml }<ul class="box-nr-table"><li>${typeNames[item.TYPE]}</li><li>${item['SUM(FLOORAGE)']}</li><li>${item['COUNT(*)']}处</li></ul>`
      // $("#totalXX").html(`<ul class="box-nr-table"><li>${typeNames[item.TYPE]}</li><li>${item['SUM(FLOORAGE)']}平方米</li><li>${item['COUNT(*)']}处</li></ul>`)
    })
    $('#regionXX').html(totalHtml)
    constructionList = streetInfo
    for (let key in streetInfo) {
      if (key != 'listAll'){
        var rowHtml = ``
        streetInfo[key].forEach(item => {
          rowHtml = rowHtml + ` <ul class="box-nr-table">
            <li>${typeNames[item.TYPE]}</li>
            <li>${item['SUM(FLOORAGE)']}</li>
            <li>${item['COUNT(*)']}处</li>
          </ul>`
        })
        $('#regionXX').append(
          `<div class="box-nr-tit" onclick="clcikTown('${key}',1)">
          <img src="images/dingwei.png" />
          ${key}
        </div>
        <div class="box-nr-xx">
          <ul class="box-nr-table box-nr-table-header">
            <li>工程状态</li>
            <li>总面积(㎡)</li>
            <li>总数量</li>
          </ul>
         ${rowHtml}
        </div>`
        )
      }
      
    }
  })
}
function attribute (e) {
  window.open("/ditu/ztcjg/ztcjg2.html?" + e.target.customData._url)
}
// 获取全部工地地图
// Clitype 是否第一次
function getAllWhole (stateType, Clitype,date) {
  let times = getFLDay(date.substr(0, 4), date.substr(5, 2))
  let param = {
    state: stateType,
    beginTime: times[0],
    endTime: times[1]
  }
  indexAjax('GET', api.findAllProject, param, function (res) {
    if (Clitype) {
      // $("#totalNum").html(`${res.list[0].total}`)
    }
    var streetInfo = res.list[0].streetInfo
    var listAll = res.list[0].listAll
    var typeNames = {
      '1': '在建工地 ',
      '2': '市镇',
      '3': '装修',
      '5': '拆迁工地'
    }
    listAll.forEach(item => {
      $("#totalXX").html(`<ul class="box-nr-table"><li>${typeNames[item.TYPE]}</li><li>${item['SUM(FLOORAGE)']}(㎡)</li><li>${item['COUNT(*)']}处</li></ul>`)
    })
    //城镇
    // streetInfo[0]
    constructionList = streetInfo[0]
    for (let key in streetInfo[0]) {
      var rowHtml = ``
      streetInfo[0][key].forEach(item => {
        rowHtml = rowHtml + ` <ul class="box-nr-table">
            <li>${typeNames[item.type]}</li>
            <li>${item.sumAre}</li>
            <li>${item.count}处</li>
          </ul>`
      })
      $('#regionXX').html(
        `<div class="box-nr-tit" onclick="clcikTown('${key}',1)">
          <img src="images/dingwei.png" />
          ${key}
        </div>
        <div class="box-nr-xx">
          <ul class="box-nr-table box-nr-table-header">
            <li>工程状态</li>
            <li>总面积(㎡)</li>
            <li>总数量</li>
          </ul>
         ${rowHtml}
        </div>`
      )
    }
    coorNum = 0
    res.list[0].allLocation.forEach(item => {
      let coordinatesObj = JSON.parse(item.FANGWU)
      getConstruction(item.TYPE, [coordinatesObj.coordinates[0], { id: item.BUILDINGSITENUM, lat: item.CENTRALLAT, lon: item.CENTRALLON }])
    })
  })
}

//锁定工地数
function getLockNum (cun) {
  lockAjax('GET', api.getLockSite, {}, function (res) {
    if (cun) {
      map.clearOverlays();
      res.forEach(item => {
        let coordinatesObj = JSON.parse(item.FANGWU)
        getConstruction(item.TYPE, [coordinatesObj.coordinates[0], { id: item.BUILDINGSITENUM, lat: item.CENTRALLAT, lon: item.CENTRALLON }])
      })
    } else {
      let lockLength = res.length
      $("#LockNum").append(lockLength)
    }
  })
}
//活动预警
function warning (type, month, Clitype, cli) {
  map.clearOverlays();
  let param = {
    type: type,
    month: month
  }
  var typeNames = {
    '0': '出入口抓拍 ',
    '2': '卫星定位研判',
    '3': '群众举报',
    '4': '卫星遥感影像'
  }
  WornkAjax('GET', api.WarningSite, param, function (res) {
    var listAll = res.siteAnalysisAll
    var siteAnalysisStreet = res.siteAnalysisStreet
    if (Clitype){
      $("#warnNum").text(`${res.total}`)
      return false
    }
    $("#warnNum").text(`${res.total}`)
    if (cli) {
      if (res.data.length == 0) {
        $('#regionXX').html('')
        return false
      }
      res.data.forEach(item => {
        let coordinatesObj = JSON.parse(item.SITE_COORDINATES)
        getConstruction(item.TYPE, [coordinatesObj.coordinates[0], { id: item.SITE_ID, lat: item.SITE_LAT, lon: item.SITE_LON }])
      })
      var totalHtml = `<div class="box-nr-tit">
          <img src="images/dingwei.png" />
          全区情况
        </div>
        <div class="box-nr-xx" id="totalXX">
          <ul class="box-nr-table box-nr-table-header">
            <li>工程状态</li>
            <li>总面积(㎡)</li>
            <li>总数量</li>
          </ul>
        </div>`
      // 总情况数
      listAll.forEach(item => {
        totalHtml = totalHtml + `<ul class="box-nr-table"><li>${typeNames[item.SITE_TYPE]}</li><li>${item['SITE_FLOORAGE']}(㎡)</li><li>${item['COUNT']}处</li></ul>`
        // $("#totalXX").html(`<ul class="box-nr-table"><li>${typeNames[item.SITE_TYPE]}</li><li>${item['SITE_FLOORAGE']}(㎡)</li><li>${item['COUNT']}处</li></ul>`)
      })
      $('#regionXX').html(totalHtml)
      // 街道数据
      
      activitiesList = siteAnalysisStreet
      siteAnalysisStreet.forEach((item,index) => {
        var rowHtml = ``
        item.SITE_STREET_DATA.forEach(obj => {
          rowHtml = rowHtml + ` <ul class="box-nr-table">
            <li>${typeNames[obj.type]}</li>
            <li>${obj.floorage}</li>
            <li>${obj.count}处</li>
          </ul>`
        })
        $('#regionXX').append(
          `<div class="box-nr-tit" onclick="clcikTown(${index},2)">
          <img src="images/dingwei.png" />
          ${item.SITE_STREET}
        </div>
        <div class="box-nr-xx">
          <ul class="box-nr-table box-nr-table-header">
            <li>工程状态</li>
            <li>总面积(㎡)</li>
            <li>总数量</li>
          </ul>
         ${rowHtml}
        </div>`
        )
      })
    }

  })
}
// 根据邮编查询 经纬
function clcikTown (key,type) {
  console.log(constructionList[key], activitiesList[key])
  var typeNames = {
    '1': '在建工地 ',
    '2': '市镇',
    '3': '装修',
    '5': '拆迁工地'
  }
  var activitiesNames = {
    '0': '出入口抓拍 ',
    '2': '卫星定位研判',
    '3': '群众举报',
    '4': '卫星遥感影像'
  }
  var ZIP = ''
  $("#realAnalysis")[0].style.display = "block"
  $("#Regional")[0].style.display = "none"
  if(type == 1){
    ZIP = constructionList[key][0].zip
    var realHtml =``
    constructionList[key].forEach(item=>{
      realHtml = realHtml +`<div class="gc-list">
          <div class="gc-name">${typeNames[item.TYPE]}：</div>
          <div class="gc-xx">
            <span>${item['SUM(FLOORAGE)']}</span>㎡
            <span>${item['COUNT(*)']}</span>处
          </div>
        </div>`
    })
    $("#realAnalysis .box-nr").html(` <div class="box-nr">
        <div class="box-nr-tit box-nr-tit-gcs">
          <div class="gcs-title">
            <img src="images/dingwei.png" />
            ${key}
          </div>
        </div>
        ${realHtml}
      </div>`)
  }else if(type == 2){
    ZIP = activitiesList[key].SITE_ZIP
    var activitHtml = ``
    activitiesList[key].SITE_STREET_DATA.forEach(item => {
      activitHtml = activitHtml + `<div class="gc-list">
          <div class="gc-name">${activitiesNames[item.type]}：</div>
          <div class="gc-xx">
            <span>${item.floorage}</span>㎡
            <span>${item.count}</span>处
          </div>
        </div>`
    })
    $("#realAnalysis .box-nr").html(` <div class="box-nr">
        <div class="box-nr-tit box-nr-tit-gcs">
          <div class="gcs-title">
            <img src="images/dingwei.png" />
            '${activitiesList[key].SITE_STREET}'
          </div>
        </div>
        ${activitHtml}
      </div>`)
  }
  districtAreaData.forEach(item=>{
    if (ZIP == item.JDCODE){
      // let point = item.center_point.lng + ',' + item.center_point.lat
      map.panTo(new BMap.Point(item.center_point.lng, item.center_point.lat));
    }
  })
}
// 街道返回


// 获取当前日期
function getNewDate () {
  var myDate = new Date();
  var tYear = myDate.getFullYear();
  var tMonth = myDate.getMonth();
  var m = tMonth + 1;
  if (m.toString().length == 1) {
    m = "0" + m;
  }
  return tYear + '-' + m;
}
// 获取年月日 星期
function getCurrentDate () {
  var myDate = new Date();
  var year = myDate.getFullYear(); //年
  var month = myDate.getMonth() + 1; //月
  var day = myDate.getDate(); //日
  var days = myDate.getDay();
  switch (days) {
    case 1:
      days = '星期一';
      break;
    case 2:
      days = '星期二';
      break;
    case 3:
      days = '星期三';
      break;
    case 4:
      days = '星期四';
      break;
    case 5:
      days = '星期五';
      break;
    case 6:
      days = '星期六';
      break;
    case 0:
      days = '星期日';
      break;
  }
  $("#headDate").append(`<span>${year}年${month}月${day}日</span><span>${days}</span> `)

}

// 计算当月的起始位置和末尾日期
function getFLDay (year, month) {
  var fristTime = " 00:00:00"
  var lastTime = " 23:59:59"
  var new_year = year;    //取当前的年份         
  var new_month = month;//取下一个月的第一天，方便计算（最后一天不固定）         
  if (month > 12) {
    new_month -= 12;        //月份减         
    new_year++;            //年份增         
  }
  var new_date = new Date(new_year, new_month, 1);                //取当年当月中的第一天         
  let lastDate = (new Date(new_date.getTime() - 1000 * 60 * 60 * 24)).getDate()
  return [`${year}-${month}-01${fristTime}`, `${year}-${month}-${lastDate}${lastTime}`]
} 

// 获取指定月的上一个月
function getPreMonth (date) {
  var arr = date.split('-');
  var year = arr[0]; //获取当前日期的年份
  var month = arr[1]; //获取当前日期的月份
  var days = new Date(year, month, 0);
  days = days.getDate(); //获取当前日期中月的天数
  var year2 = year;
  var month2 = parseInt(month) - 1;
  if (month2 == 0) {
    year2 = parseInt(year2) - 1;
    month2 = 12;
  }
  if (month2 < 10) {
    month2 = '0' + month2;
  }
  var t2 = year2 +month2;
  return t2;
}
// 判断网络图片是否存在
function validateImage (url) {
  var xmlHttp;
  if (window.ActiveXObject) {
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  else if (window.XMLHttpRequest) {
    xmlHttp = new XMLHttpRequest();
  }
  xmlHttp.open("Get", url, false);
  xmlHttp.send();
  if (xmlHttp.status == 404 || xmlHttp.status == 500)
    return false;
  else
    return true;
}


